<?php
include 'includes/db.php';
session_start();

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => '用户未登录']);
    exit;
}

$user_id = $_SESSION['user_id'];
$cost = 0.05;

$stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if ($user && $user['balance'] >= $cost) {
    $new_balance = $user['balance'] - $cost;
    $stmt = $pdo->prepare("UPDATE users SET balance = ? WHERE id = ?");
    $stmt->execute([$new_balance, $user_id]);

    $videoUrl = $_GET['url'] ?? '';

    if (empty($videoUrl)) {
        echo json_encode(['success' => false, 'message' => '未提供短视频链接']);
        exit;
    }

    $host = "https://xzdx.top/api/duan/";
    $method = "GET";
    $url = $host . "?url=" . urlencode($videoUrl);

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);

    $response = curl_exec($curl);
    if (curl_errno($curl)) {
        echo json_encode(['success' => false, 'message' => 'CURL error: ' . curl_error($curl)]);
        curl_close($curl);
        exit;
    }

    curl_close($curl);

    $result = json_decode($response, true);
    echo json_encode(['success' => true, 'data' => $result['data']]);
} else {
    echo json_encode(['success' => false, 'message' => '余额不足']);
}